package com.fhz.day19.utils;

import android.media.MediaPlayer;

import com.fhz.day19.model.Song;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * 时间:2022/5/12
 *
 * @author mrfeng
 * 简述:
 * 1,管理mp
 * 2,管理数据源
 * 3,设备播放的各种方法
 *
 */
public class MusicUtils {

    private MusicUtils(){
    }

    private static MusicUtils musicUtils = null;

    public static MusicUtils getInstance(){
        if (musicUtils == null){
            synchronized (MusicUtils.class){
                if (musicUtils == null){
                    musicUtils = new MusicUtils();
                }
            }
        }
        return musicUtils;
    }

    //mp
    private MediaPlayer mediaPlayer = new MediaPlayer();
    private int index = 0;
    //数据源在使用的时候,一定要初始化
    private List<Song.Data> dataList;

    public List<Song.Data> getDataList() {
        return dataList;
    }

    public int getIndex() {
        return index;
    }

    public void setDataList(List<Song.Data> dataList) {
        this.dataList = dataList;
    }

    public void play(int i){
        index = i;
        mediaPlayer.reset();
        try {
            //空指针是怎么回事呢?
            mediaPlayer.setDataSource(dataList.get(i).getData());
            mediaPlayer.prepareAsync();
            mediaPlayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
                @Override
                public void onPrepared(MediaPlayer mp) {
                    mediaPlayer.start();
                }
            });
        } catch (IOException e) {
            e.printStackTrace();
        }

        //改变图片和名词
        change();
    }

    private void change() {

    }

    public String getTitle(){
        return dataList.get(index).getTitle();
    }

    public String getImageUrl(){
        return dataList.get(index).getAlbum();
    }

    public void pause(){
        mediaPlayer.pause();
    }

    public void restart(){
//        if(mediaPlayer.isPlaying()){
//            mediaPlayer.pause();
//        }else{
//            mediaPlayer.start();
//        }
        mediaPlayer.start();
    }

    public void stop(){
        mediaPlayer.stop();
    }

    public int getCurrentPostion(){
        return mediaPlayer.getCurrentPosition();
    }

    public int getMax(){
        return mediaPlayer.getDuration();
    }

    public void seekTo(int progress){
        mediaPlayer.seekTo(progress);
    }

    public void next(){
        //注意索引越界的问题 //周杰伦
        index++;
        play(index);
    }
}

